﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XPathPlugin.XPathTreeUtils
{
    static class XPathTreeVisualizer
    {
        private static readonly string QuadroSpace = "    ";

        /// <summary>
        /// Gets string representing XPathTree tree
        /// </summary>
        /// <param name="tree">Tree to represent</param>
        /// <returns>string</returns>
        public static string XPathTree2String(XPathTree tree)
        {
            return XPathTree2String(tree, false);
        }

        /// <summary>
        /// Gets string representing XPathTree tree. 
        /// </summary>
        /// <param name="tree">Tree to represent</param>
        /// <param name="debug">If return debug string</param>
        /// <returns>string</returns>
        public static string XPathTree2String(XPathTree tree, bool debug)
        {
            return XPathTree2String(tree as XPathNode, debug);
        }

        /// <summary>
        /// Gets string representing XPathNode tree. 
        /// </summary>
        /// <param name="node">node to represent</param>        
        /// <returns>string</returns>
        public static string XPathTree2String(XPathNode node)
        {
            return XPathTree2String(node, false);            
        }

        /// <summary>
        /// Gets string representing XPathNode tree. 
        /// </summary>
        /// <param name="node">node to represent</param>
        /// <param name="debug">If return debug string</param>
        /// <returns>string</returns>
        public static string XPathTree2String(XPathNode node, bool debug)
        {
            if (node == null)
                return "null";

            StringBuilder sb = new StringBuilder();
            StringBuilder value = null;
            IEnumerator<XPathNode> nodeEnumeration = node.GetDepthFirstEnumerator();

            // Walk in tree
            while (nodeEnumeration.MoveNext())
            {
                XPathNode _node = nodeEnumeration.Current;
                int nodeDepth = _node.Depth;
                value = new StringBuilder(30);

                for (int depth = 0; depth < nodeDepth; depth++)
                    value.Append(QuadroSpace);
                
                // Build value
                value.Append(_node.Value.Value)
                     .Append("; Type=")
                     .Append(_node.Value.Type.ToString());                     

                // Add debug string
                if (debug)
                    value.Append("; Debug=")
                         .Append(_node.Value.Debug);

                value.AppendLine();
                sb.Append(value);
            }

            return sb.ToString();
        }
    }
}
